package com.carnation.servlet;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.carnation.bean.FileInfo;
import com.carnation.service.FileService;
import com.carnation.service.impl.FileServiceImpl;
import com.carnation.utils.Json;
import com.carnation.utils.SessionInfo;
import com.google.gson.Gson;

public class UploadFileServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(UploadFileServlet.class);
//	private MenuFileUtril menuFileUtril = new MenuFileUtril();

	@Override
	protected void doGet(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) {
		doPost(httpServletRequest, httpServletResponse);
	}

	@SuppressWarnings("rawtypes")
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
		Json json = new Json();
		String msg = null;
		String status = null;
		String catalogId = null;
		String description = null;
		String remark = null;
		String name = null;
		String username = null;
		long size = 0L;
		String type = null;
		Object obj = null;
		FileItem fileItem = null;
		SessionInfo sessionInfo = (SessionInfo) httpServletRequest.getSession().getAttribute("sessionInfo");
		username = sessionInfo.getLoginName();
		FileService fileService = new FileServiceImpl();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(httpServletRequest);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					if (item.getFieldName().equals("catalogid")) {
						catalogId = item.getString("UTF-8");
					} else if (item.getFieldName().equals("remark")) {
						remark = item.getString("UTF-8");
					} else if (item.getFieldName().equals("description")) {
						description = item.getString("UTF-8");
					} else {
						logger.info("未知参数  " + item.getFieldName() + ":"
								+ item.getString("UTF-8"));
					}
					System.out.println("表单参数名:" + item.getFieldName()
							+ "，表单参数值:" + item.getString("UTF-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						System.out.println("上传文件的大小:" + item.getSize());
						System.out.println("上传文件的类型:" + item.getContentType());
						// item.getName()返回上传文件在客户端的完整路径名称
						System.out.println("上传文件的名称:" + item.getName());
						name = item.getName();
						size = item.getSize();
						if(item.getName().lastIndexOf(".") == -1){
							type = "";
						}
						else{
							type = item.getName().substring(item.getName().lastIndexOf("."));
						}
						fileItem = item;
						// File tempFile = new File(item.getName());
						// File file = new File("E:\\", tempFile.getName());
						// item.write(file);
						// httpServletRequest.setAttribute("upload.message",
						// "上传文件成功！");
					} else {
						// httpServletRequest.setAttribute("upload.message",
						// "没有选择上传文件！");
						logger.info("跳转到上传失败");
					}
				}
			}
			if (name == null || catalogId == null || description == null
					|| username == null || fileItem == null || size == 0 || type == null) {
				logger.info("参数收集失败");
				msg = "系统发生错误，请联系系统管理员";
				status = "500";
			} else {
				if (fileService.checkFileExistByCatalogIdAndName(catalogId,	name)) {
					msg = "该文件名已存在,不能上传";
					status = "300";
				} else {
					String storePath = fileService
							.getStorePathByCatalogId(catalogId);
					logger.info(storePath);
					File file = new File(storePath, name);
					fileItem.write(file);
					SimpleDateFormat format = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					String uploadTime =format.format(new Date()); 
					FileInfo fileInfo = new FileInfo(catalogId, name, username,
							uploadTime, description, remark,size,type);
					fileService.writeFileInfo(fileInfo);
					msg = "上传成功";
					status = "200";
					obj = fileInfo;
					logger.info("IP地址为" + httpServletRequest.getRemoteHost() +"用户" + username + "在" + uploadTime + "上传了一个名为"+ name +"的文件");
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			httpServletRequest.setAttribute("upload.message", "上传文件失败！");
		}
		json.setMsg(msg);
		json.setObj(obj);
		json.setStatus(status);
		Gson gson = new Gson();
		httpServletResponse.setCharacterEncoding("UTF-8");
		try {
			httpServletResponse.getWriter().write(gson.toJson(json));
			httpServletResponse.getWriter().close();
		} catch (Exception e) {
			logger.error("返回响应报文失败", e);
		}

	}
}
